package com.example.springbootdemo.i18n;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.i18n.LocaleContextHolder;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;

public class CustomLocalDateTimeSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(Date localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 获取用户选择的Locale
        Locale userLocale = LocaleContextHolder.getLocale();
        // 根据用户Locale选择时区
        ZoneId zoneId = determineTimeZone(userLocale);

        ZonedDateTime originDate = ZonedDateTime.ofInstant(localDateTime.toInstant(), ZoneId.systemDefault());
        ZonedDateTime targetDate = originDate.withZoneSameInstant(zoneId);

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        jsonGenerator.writeString(targetDate.format(dateTimeFormatter));
    }

    private ZoneId determineTimeZone(Locale userLocale) {
        // 根据用户Locale选择时区，你可以根据实际需求进行实现
        // 这里只是一个简单的示例
        if (userLocale.equals(Locale.CHINA)) {
            return ZoneId.of("Asia/Shanghai");
        } else if (userLocale.equals(Locale.US)) {
            return ZoneId.of("America/New_York");
        } else {
            return ZoneId.systemDefault();
        }
    }
}